package ldh.text.util;

import ldh.text.vo.FindPosition;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtil {

    /**
     * 查找有多少个
     * @param content
     * @param findStr  查找字符
     * @return
     */
    public static int totalFind(String content, String findStr) {
        Pattern pattern = Pattern.compile(findStr);
        Matcher matcher = pattern.matcher(content);
        int total = 0;
        while(matcher.find()) {
            total ++;
        }
        return total;
    }

    public static int find(String content, String findStr, List<FindPosition> result) {
        Pattern pattern = Pattern.compile(findStr);
        Matcher matcher = pattern.matcher(content);
        int total = 0;
        int size = content.length();
        while(matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            int aStart = start - 50 < 0 ? 0 : start - 50;
            int aEnd = end + 50 > size ? size : end + 50;
            result.add(new FindPosition(start, end, content.substring(aStart, aEnd)));
            total ++;
        }
        return total;
    }

    public static int find(Pattern pattern, String content, List<FindPosition> result) {
        Matcher matcher = pattern.matcher(content);
        int total = 0;
        int size = content.length();
        while(matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            int aStart = start - 50 < 0 ? 0 : start - 50;
            int aEnd = end + 50 > size ? size : end + 50;
            result.add(new FindPosition(start - aStart, start - aStart + end-start, content.substring(aStart, aEnd)));
            total ++;
        }
        return total;
    }

    public static int find(Pattern pattern, String content, List<FindPosition> result, int fetchSize) {
        Matcher matcher = pattern.matcher(content);
        int total = 0;
        int size = content.length();
        while(matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            int aStart = start - fetchSize < 0 ? 0 : start - fetchSize;
            int aEnd = end + fetchSize > size ? size : end + fetchSize;
            result.add(new FindPosition(start-aStart, start - aStart + end-start , content.substring(aStart, aEnd)));
            total ++;
        }
        return total;
    }
}
